(function() {
    var _title_map = {
        "/main": "首页",
        "/goods_list": {
            key: "id",
            value_map: {
                "*": "最新上架",
                "2": "销量最高"
            }
        },
        "/storeinfo": "简介",
        "/cart": "购物车",
        "/goods_details": "商品详情",
        "/pay": "评价管理",
        "/sign_in": {
            key: "id",
            value_map: {
                "*": "用户登录",
                "2": "用户注册"
            }
        }
    };

    function _AppReady_init() {
        Path.on("/:page?", function(_current_location) {
            var title_info = _title_map[Path._current_page];
            if (typeof title_info === "string") {
                App.set("Path.document_title", title_info);
            } else if (typeof title_info === "object") {
                var _val = Path.getQuery(title_info.key);
                App.set("Path.document_title", title_info.value_map[_val] || title_info.value_map["*"]);
            };
            console.log("USER Document title:", App.get("Path.document_title"));
            if (!(Path._current_page == "/sign_in")) {
                Cookies.set("$Cache.top.cb_url", encodeURIComponent(location.href));
            };


        });

        // 搜索
        App.set("$Event.open_search", function() {
            Path.jump("/searchset.html?q=" + App.get("$Cache.search_text"));
            App.set("$Cache.search_text", "");
        });
        // 添加到购物车
        App.set("$Event.goods_list.add_to_cart", function(e, vm) {
            console.log(vm.get("_id"));
            if (!App.get("loginer")) {
                myConfirm("添加商品前请先登陆！", function() {
                    Path.jump("/sign_in.html?cb_url=" + Cookies.get("$Cache.top.cb_url"));
                });
            } else {
                var cart_item = {
                    goods_id: vm.get("_id"),
                    num: 1
                };
                goodsCart.add_to_cart(vm.get("_id"), 1, _get_cart_success)
            };
        });
        // 跳转到购物车
        App.set("$Event.top.jumpToCart", function() {
            if (!App.get("loginer")) {
                myConfirm("请先登陆后以访问购物车。", function() {
                    Path.jump("/sign_in.html?cb_url=" + Cookies.get("$Cache.top.cb_url"));
                });
                return;
            };
            Path.jump("/cart.html");
        });

        // 未开放功能
        App.set("$Event.top.noPair", function() {
            alert("success", "此功能暂未开放，敬请期待");
        });

        // // 获取坐标
        // if (navigator.geolocation) {
        //  navigator.geolocation.getCurrentPosition(function(position) {
        //      var coordinate = position.coords;
        //      App.set("$Cache.top.coordinate", position.coords);
        //      var _url = "http://route.showapi.com/9-5?showapi_appid=7129&showapi_sign=aee1708ab21e4e0ba19d71aed4e3cf39&showapi_timestamp=" + init_time() + "&from=3&lat=" + coordinate.latitude + "&lng=" + coordinate.longitude;
        //      $.getJSON(_url, function(weatherResponse) {
        //          App.set("$Cache.user.localcity.weather", weatherResponse.showapi_res_body.now)
        //          App.set("$Cache.main.location_city", weatherResponse.showapi_res_body.cityInfo.c5);
        //      });
        //  }, function(error) {
        //      switch (error.code) {
        //          case error.TIMEOUT: // code==3
        //              myConfirm("gps连接超时，如需使用请刷新重试！");
        //              break;
        //          case error.PERMISSION_DENIED: //code==1
        //              myConfirm("您已拒绝了使用gps位置共享服务，我们仅能由IP地址为您提供有限的位置服务");
        //              break;
        //          case error.POSITION_UNAVAILABLE: // code==2
        //              myConfirm("亲爱的火星网友，非常抱歉，我们暂时无法为您所在的星球提供位置服务");
        //              break;
        //      }
        //      // 获取本机ip和城市信息
        //      var _url = "http://route.showapi.com/632-1?showapi_appid=7129&showapi_sign=aee1708ab21e4e0ba19d71aed4e3cf39&showapi_timestamp=" + init_time();
        //      $.getJSON(_url, function(ipResponse) {
        //          console.log(ipResponse.showapi_res_body.city);
        //          App.set("$Cache.main.location_city", ipResponse.showapi_res_body.city);
        //          var weather_url = "http://route.showapi.com/9-2?showapi_appid=7129&showapi_sign=aee1708ab21e4e0ba19d71aed4e3cf39&showapi_timestamp=" + init_time() + "&area=" + ipResponse.showapi_res_body.city;
        //          $.getJSON(weather_url, function(weatherResponse) {
        //              console.log(weatherResponse.showapi_res_body);
        //              App.set("$Cache.user.localcity.weather", weatherResponse.showapi_res_body.now);
        //          });
        //      });
        //  });
        // };

    };
    jSouper.App ? _AppReady_init() : eventManager.on("!AppReady", _AppReady_init);



    var goodsCart = {
        add_to_cart: function(goods_id, num, succ_cb, err_cb) {
            num = ~~num || 1;
            if (num < 0) {
                num = 0;
            };
            var cart_item = {
                goods_id: goods_id,
                num: 1
            };
            coAjax.post(appConfig.user.cart, cart_item, function(result) {
                alert("success", "商品已添加到购物车");
                succ_cb && succ_cb.apply(this, arguments);
            }, function(errorCode, xhr, errorMsg) {
                alert("error", errorMsg);
                err_cb && err_cb.apply(this, arguments);
            });
        }
    };

    function _get_cart_success(result) {
        var cart_detail = result.result;
        App.set("user.cart_detail", cart_detail);
        Path.jump("/cart.html");
    };


}());

// 获取时间戳函数
function init_time() {
    var now = new Date();
    var year = now.getFullYear();
    var month = (now.getMonth() + 1 > 9) ? now.getMonth() : ("0" + (now.getMonth() + 1));
    var days = now.getDate() > 9 ? now.getDate() : ("0" + now.getDate());
    var hours = now.getHours() > 9 ? now.getHours() : ("0" + now.getHours());
    var minutes = now.getMinutes() > 9 ? now.getMinutes() : ("0" + now.getMinutes());
    var seconds = now.getSeconds() > 9 ? now.getSeconds() : ("0" + now.getSeconds());
    return year + "" + month + "" + days + "" + hours + "" + minutes + "" + seconds;
};